#include <stdio.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>


int main(int argc, char ** argv)
{
    pid_t pid;
    char buff[1024];
    char *arg[10];//最多输入10个参数
    int ret;
    int i ;
AGAIN:
    printf("myshell:%s$ ",getcwd(NULL,1024));
    fflush(stdout);
    ret = read(STDIN_FILENO,buff,sizeof(buff)-1);
    if(ret == -1)
    {
        perror("read");
        exit(1);
    }
    buff[ret - 1] = '\0';

    //exit
    if(strcmp(buff,"exit") == 0)
    {
        exit(0);
    }

    i = 0;
    arg[i] = strtok(buff, " ");
    while(arg[i] != NULL)
    {
        if(++i >= sizeof(arg))
        {
            break;
        }
        arg[i] = strtok(NULL, " ");
    }

    //cd
    if(i == 2 && strcmp(arg[0],"cd") == 0)
    {
        chdir(arg[1]);
        goto AGAIN;
    }

    //begin create cild process
    pid = fork();
    if(pid == 0)
    {
        execvp(arg[0],arg);
        return 0;
    }
    else if(pid != -1)
    {
        wait(NULL);
        goto AGAIN;

    }else
    {
        perror("fork");
    }

    return 0;
}
